import axios from 'axios'
import axiosExtra from 'axios-extra'
import {getToken, removeToken} from "@/utils/token";
import {ElMessage, ElMessageBox} from "element-plus";
import {LOGIN_PATH} from "@/const/RouterPathConst";

const VITE_APP_BASE_API = import.meta.env.VITE_APP_BASE_API

const http = axios.create({
    baseURL: VITE_APP_BASE_API
})

http.interceptors.request.use(config => {
    let token = getToken();
    if (token) {
        config.headers.authorization = token
    }

    return config;
})
http.interceptors.response.use(response => {
        let data = response.data
        if (data.code === "A10000") {
            ElMessageBox.confirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录',
                '系统提示',
                {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    removeToken()
                    location.href = LOGIN_PATH;
                })
                .catch(() => {
                })
            return
        }

        if (data.code !== "200" && response.status !== 200) {
            console.log(response, 5555)
            ElMessage({
                type: "error",
                message: data.msg
            })
        }

        return response.data
    },
    error => {
        ElMessage({
            type: "error",
            message: "系统异常"
        })
        return Promise.reject(error);
    }
)

const getSysFileList = (path) => {
    return http.get(`/file/listFiles`, {
        params: {
            path: path
        }
    })
}

const login = (username, password) => {
    return http.post('/login', {username, password})
}

const validUserExist = () => {
    return http.post(`/validUserExist`)
}

const registUser = (username, password) => {
    return http.post('/registUser', {username, password})
}

const downloadFile = (path) => {
    return http.get(`/file/download?path=${encodeURIComponent(path)}`)
}
export {
    getSysFileList,
    login,
    validUserExist,
    registUser,
    downloadFile
}
